import React, { useCallback, useEffect, useState } from 'react'
import {
  Card,
  Breadcrumb,
  Button,
  Radio,
  Form,
  DatePicker,
  Select,
  Space,
  Table,
  Tag,
  Modal,
  message
} from 'antd'
import { Link, useNavigate } from 'react-router-dom'
import 'moment/locale/zh-cn'
import locale from 'antd/es/date-picker/locale/zh_CN'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { channels, getArticles, delArticles } from '@/api/article'
import img404 from '@/assets/error.png'

// 优化文章状态的处理
const articleStatus = {
  0: { color: 'yellow', text: '草稿' },
  1: { color: '#ccc', text: '待审核' },
  2: { color: 'green', text: '审核通过' },
  3: { color: 'red', text: '审核失败' }
}

function Article() {
  const navigate = useNavigate()
  // 数据列表
  const [datas, setDatas] = useState({
    page: 1,
    per_page: 10,
    total_count: 0,
    results: []
  })
  // 频道数据
  const [channel, setChannel] = useState([])
  // 筛选条件
  //筛选数据
  const onFinish = async ({ status, channel, date }) => {
    const params = {
      status: status === -1 ? null : status,
      channel_id: channel,
      page: 1,
      per_page: datas.per_page,
      begin_pubdate: '',
      end_pubdate: ''
    }
    if (!!date) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD HH:mm:ss')
      params.end_pubdate = date[1].format('YYYY-MM-DD HH:mm:ss')
    }
    setDatas({ ...datas, ...params, page: 1 })
    await getArt(params)
  }

  // 获取频道列表
  const getChannels = useCallback(async () => {
    const { data } = await channels()
    setChannel(data.channels)
  }, [])

  // 获取文章列表
  const getArt = useCallback(async (params) => {
    const { data } = await getArticles(params)
    setDatas(data)
  }, [])

  const changePage = (page, per_page) => {
    setDatas({
      ...datas,
      page,
      per_page
    })
  }

  // 删除文章
  const delArticle = (id) => {
    Modal.confirm({
      title: '提示',
      Content: '确认删除吗?',
      icon: <DeleteOutlined />,
      onOk: async () => {
        await delArticles(id, false)
        message.success('删除成功')
        await getArt(datas)
      }
    })
  }

  useEffect(() => {
    getChannels() // 调用获取频道接口
  }, [getChannels])

  useEffect(() => {
    getArt(datas) // 调用获取文章列表
  }, [getArt, datas.page])

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return (
          <img
            src={cover.images[0] || img404}
            width={200}
            height={150}
            alt=""
          />
        )
      }
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => (
        <Tag color={articleStatus[data].color}>{articleStatus[data].text}</Tag>
      )
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate'
    },
    {
      title: '阅读数',
      dataIndex: 'read_count'
    },
    {
      title: '评论数',
      dataIndex: 'comment_count'
    },
    {
      title: '点赞数',
      dataIndex: 'like_count'
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => {
                navigate(`/layout/publish/${data.id}`)
              }}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => {
                delArticle(data.id)
              }}
            />
          </Space>
        )
      }
    }
  ]

  return (
    <div>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          name="basic"
          onFinish={onFinish}
          initialValues={{
            status: -1
          }}
        >
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel">
            <Select placeholder="请选择文章频道" style={{ width: 120 }}>
              {channel.map((item, i) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <DatePicker.RangePicker locale={locale}></DatePicker.RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={`根据筛选条件共查询到${datas.total_count}条结果`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={datas.results}
          pagination={{
            position: ['bottomCenter'],
            current: datas.page,
            pageSize: datas.per_page,
            total: datas.total_count,
            onChange: changePage
          }}
        />
      </Card>
    </div>
  )
}

export default Article
